﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.BasicList
{
    public partial class panel_Maker : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private SqlConnection masterConnection;
        
        public panel_Maker()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.masterConnection = new SqlConnection(mySetting.DB2ConnectionString);

            LoadData();

            this.Maker.DoubleClick += Maker_DoubleClick;
            this.Maker.PopupMenuShowing += Maker_PopupMenuShowing;
            this.makerContext.ItemClicked += makerContext_ItemClicked;
        }

        private void callEditForm()
        {            
            DataRow row = Maker.GetFocusedDataRow();
            frm_Edit_Maker editForm = new frm_Edit_Maker();
            editForm.maker_id = row[0].ToString();
            if (editForm.LoadData())
            {                
                editForm.ShowDialog();
                LoadData();
            }
            else
            {
                MessageBox.Show("Cannot load data for selected record");
            } 
        }

        void Maker_DoubleClick(object sender, EventArgs e)
        {
            callEditForm();
        }

        void makerContext_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.makerContext.Hide();            
            switch (e.ClickedItem.Name)
            {
                case "importSelection":
                    importDatabase();
                    break;
                case "addSelection":
                    frm_Add_Maker add_form = new frm_Add_Maker();
                    add_form.ShowDialog();
                    LoadData();
                    break;
                case "editSelection":
                    callEditForm();
                    break;
                case "deleteSelection":
                    deleteRecord();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        void Maker_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.makerContext.Show(MousePosition);
        }

        ///////////////////////////////////
        /// Load Data From Local Database
        ///////////////////////////////////
        private void LoadData()
        {
            DataSet sourceDataSet = new DataSet();
            INISettings mySettings = new INISettings();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySettings.SQLConnectionString;
            string sql = "SELECT MakerID, MakerName, EnglishName FROM [222_Maker]";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridMaker.DataSource = sourceDataSet.Tables[0];
                getUpdateInfo();
            }
            else
            {
                MessageBox.Show("There is no data for Maker");
                DataTable newTable = new DataTable();
                newTable.Columns.Add("MakerID", typeof(string));
                newTable.Columns.Add("MakerName", typeof(string));
                newTable.Columns.Add("EnglishName", typeof(string));
                gridMaker.DataSource = newTable;
            }
            Maker.Columns[0].Caption = "Maker ID";
            Maker.Columns[1].Caption = "Maker Name";
            Maker.Columns[2].Caption = "English Name";
            Maker.BestFitColumns();
        }

        /////////////////////////////////////
        /// Get Update Information
        /////////////////////////////////////
        private void getUpdateInfo()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT LastUpdate FROM [222_UpdateHistory] WHERE ID=5";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.updateDate.Text = dataReader["LastUpdate"].ToString();
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get update information");
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }


        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm();
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            importDatabase();
        }

        ////////////////////////////////////
        /// Update database From AS400
        ////////////////////////////////////

        private void importDatabase()
        {
            OleDbDataAdapter adp;
            DataTable excel_data = new DataTable();
            
            bool have_data = false;

            importFile.Filter = "Excel 97-2003 (.xls)|*.xls|Excel 2007-2010 (.xlsx)|*.xlsx";
            importFile.FilterIndex = 1;
            importFile.Multiselect = false;
            DialogResult userClickOK = importFile.ShowDialog();
            if (userClickOK == DialogResult.OK)
            {
                OleDbConnection excelConnection = null;
                try
                {
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        importFile.FileName + ";Extended Properties=Excel 12.0;Persist Security Info=False";
                    excelConnection = new OleDbConnection(excelConnectionString);
                    OleDbCommand cmd = new OleDbCommand("Select [MakerID],[MakerName],[EnglishName] from [Sheet1$]", excelConnection);
                    excelConnection.Open();
                    adp = new OleDbDataAdapter(cmd);
                    adp.Fill(excel_data);
                    have_data = true;
                    excelConnection.Close();
                }
                catch
                {
                    if (excelConnection.State == ConnectionState.Open)
                    {
                        excelConnection.Close();
                    }
                    have_data = false;
                    MessageBox.Show("Cannot import data from file. Please check your file");
                }
            }            

            if (have_data)
            {

                DataSet maker = new DataSet();
                string sql = null;
                SqlDataAdapter adapter;
                DataTable maker_local;
                try
                {
                    //Get Data From Local Database
                    myConnection.Open();
                    sql = "SELECT * FROM [222_Maker]";
                    SqlCommand cmd = new SqlCommand(sql, myConnection);
                    adapter = new SqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    adapter.Fill(maker, "222_Maker");
                    maker_local = maker.Tables["222_Maker"];
                    
                    foreach (DataRow excel_row in excel_data.Rows)
                    {
                        DataRow[] current_row = maker_local.Select("MakerID='" + excel_row["MakerID"].ToString() + "'");
                        if (current_row.Length > 0)
                        {
                            foreach (DataRow local_row in current_row)
                            {
                                local_row.BeginEdit();
                                local_row["MakerName"] = excel_row["MakerName"].ToString();
                                local_row["EnglishName"] = excel_row["EnglishName"].ToString();
                                local_row.EndEdit();
                            }
                        }
                        else
                        {
                            DataRow new_row = maker_local.NewRow();
                            new_row["MakerID"] = excel_row["MakerID"].ToString();
                            new_row["MakerName"] = excel_row["MakerName"].ToString();
                            new_row["EnglishName"] = excel_row["EnglishName"].ToString();
                            maker_local.Rows.Add(new_row);
                        }
                    } 


                    SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(adapter);
                    //Update to Local Database
                    adapter.Update(maker, "222_Maker");

                    adapter.Dispose();
                    cmd.Dispose();
                    myConnection.Close();

                    //Update History
                    myConnection.Open();
                    sql = "UPDATE [222_UpdateHistory] SET LastUpdate=GETDATE() WHERE ID=5";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();

                    LoadData();

                    MessageBox.Show("Database has been updated successfull.");

                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot connect to AS400");
                }
            }
        }

        private void deleteRecord()
        {
            if (MessageBox.Show("Are you really to delete selected record now?", "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DataRow row = Maker.GetFocusedDataRow();
                try
                {
                    myConnection.Open();
                    string sql = "DELETE [222_Maker] WHERE MakerID='" + row[0].ToString() + "'";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Maker deleted success.");
                    LoadData();
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot delete Maker. Please try again.");
                }
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            deleteRecord();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            frm_Add_Maker add_form = new frm_Add_Maker();
            add_form.ShowDialog();
            LoadData();
        }
    }
}
